import log4js, { getLogger } from 'log4js';
import * as path from 'path';
import { product, group, appName } from '@/common/common';

// 确保日志目录存在
const logDir = path.join(process.cwd(), 'logs');

// 自定义 JSON 布局
log4js.addLayout(
    'json',
    (config) =>
        function (logEvent) {
            return JSON.stringify({
                product: product,
                group: group,
                app: appName,
                thread: logEvent.pid?.toString() || '',
                filepath: `${logEvent.fileName || ''}:${logEvent.lineNumber || ''}`,
                uri: logEvent.context?.uri || '',
                uid: logEvent.context.uid?.toString() || '',
                trace_id: logEvent.context.traceId || '',
                log_level: logEvent.level.levelStr,
                msg: logEvent.data.join(' '),
                stack_trace: logEvent.error?.stack || '',
                timestamp: new Date(logEvent.startTime).toISOString(),
            });
        },
);

// 配置日志系统
log4js.configure({
    appenders: {
        // 控制台输出 - 使用 pattern layout
        console: {
            type: 'console',
            layout: {
                type: 'pattern',
                pattern: '%d{yyyy-MM-ddThh:mm:ss} [%p] [%c] [%X{traceId}] %m%n',
            },
        },
        // 应用日志文件 - 使用 pattern layout
        app: {
            type: 'dateFile',
            filename: path.join(logDir, 'info.log'),
            pattern: '.yyyy-MM-dd',
            compress: true,
            maxLogSize: 100 * 1024 * 1024, // 100MB
            backups: 5,
            layout: {
                type: 'json',
            },
        },
        // 应用日志文件 - 使用 pattern layout
        business: {
            type: 'dateFile',
            filename: path.join(logDir, 'business.log'),
            pattern: '.yyyy-MM-dd',
            compress: true,
            maxLogSize: 100 * 1024 * 1024, // 100MB
            backups: 5,
            layout: {
                type: 'json',
            },
        },
        perf: {
            type: 'file',
            filename: path.join(logDir, 'perf.log'),
            pattern: '.yyyy-MM-dd',
            compress: true,
            maxLogSize: 100 * 1024 * 1024, // 100MB
            backups: 5,
            layout: {
                type: 'pattern',
                pattern: `%m%n`,
            },
        },
        // 错误日志文件 - 使用 pattern layout
        error: {
            type: 'dateFile',
            filename: path.join(logDir, 'error.log'),
            pattern: '.yyyy-MM-dd',
            compress: true,
            maxLogSize: 100 * 1024 * 1024, // 100MB
            backups: 5,
            layout: {
                type: 'json',
            },
        },
        // 数据库日志文件 - 使用 pattern layout
        database: {
            type: 'dateFile',
            filename: path.join(logDir, 'database.log'),
            pattern: '.yyyy-MM-dd',
            compress: true,
            maxLogSize: 100 * 1024 * 1024, // 100MB
            backups: 5,
            layout: {
                type: 'json',
            },
        },
        // 缓存日志文件 - 使用 pattern layout
        cache: {
            type: 'dateFile',
            filename: path.join(logDir, 'cache.log'),
            pattern: '.yyyy-MM-dd',
            compress: true,
            maxLogSize: 100 * 1024 * 1024, // 100MB
            backups: 5,
            layout: {
                type: 'json',
            },
        },
        // HTTP 日志文件 - 使用 pattern layout
        http: {
            type: 'dateFile',
            filename: path.join(logDir, 'http.log'),
            pattern: '.yyyy-MM-dd',
            compress: true,
            maxLogSize: 100 * 1024 * 1024, // 100MB
            backups: 5,
            layout: {
                type: 'pattern',
                pattern: '%m',
            },
        },
    },
    categories: {
        default: {
            appenders: ['console', 'app'],
            level: process.env.LOG_LEVEL || 'info',
            enableCallStack: true,
        },
        app: {
            appenders: ['console', 'app'],
            level: process.env.LOG_LEVEL || 'info',
            enableCallStack: true,
        },
        business: {
            appenders: ['console', 'business'],
            level: process.env.LOG_LEVEL || 'info',
            enableCallStack: true,
        },
        error: {
            appenders: ['console', 'error'],
            level: 'error',
            enableCallStack: true,
        },
        database: {
            appenders: ['console', 'database'],
            level: process.env.DB_LOG_LEVEL || 'warn',
            enableCallStack: true,
        },
        cache: {
            appenders: ['console', 'cache'],
            level: process.env.CACHE_LOG_LEVEL || 'info',
            enableCallStack: true,
        },
        perf: {
            appenders: ['console', 'perf'],
            level: 'info',
            enableCallStack: true,
        },
        http: {
            appenders: ['console', 'http'],
            level: process.env.HTTP_LOG_LEVEL || 'info',
            enableCallStack: true,
        },
    },
});

const log = getLogger();
export const appLog = getLogger('app');
export const businessLog = getLogger('business');
export const errorLog = getLogger('error');
export const databaseLog = getLogger('database');
export const cacheLog = getLogger('cache');
export const httpLog = getLogger('http');
export const perfLog = getLogger('perf');

export default log;
